from datetime import datetime

from django.conf import settings
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from cart.utils import merge_cookie_cart_to_redis
from goods.models import SKU
from oauth.serializers import UserCenterInfoSerializer
from users import constants
from users.constants import USER_ADDRESS_COUNTS_LIMIT
from users.models import User
from users.serializers import UserInfoSerializer, EmailSeriazlier, UserAddressSerializer, AddressTitleSerializer, \
    UserHistorySerializer, UserHistoryAcquireSerializer
from rest_framework.generics import CreateAPIView, RetrieveAPIView, GenericAPIView, UpdateAPIView
from itsdangerous import TimedJSONWebSignatureSerializer as JWT
from itsdangerous import BadData


# GET usernames/(?P<username>\w{5,20})/count/
class UserNameCountView(APIView):
    def get(self, request, username):
        #  判断用户名是否存在
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }
        return Response(data)


# GET mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    def get(self, request, mobile):
        # 判断手机号是否存在
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)


# # POST /users/
# class UserRegister(APIView):
#     # 用户注册
#     def post(self, request):
#         # 接受参数,校验参数
#         serializer = UserInfoSerializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#
#         # 保存信息到数据库(调用序列中的create方法,没有进行密码加密,重写create方法)
#         serializer.save()
#
#         return Response(serializer.data, status=status.HTTP_201_CREATED)


# 用户注册代码优化
# POST /users/
class UserRegister(CreateAPIView):
    # 用户注册
    serializer_class = UserInfoSerializer


# # /GET /user/ 用户中心个人信息页
# class UserCenterInfoView(APIView):
#     # 用户必须登陆才能访问
#     permission_classes = [IsAuthenticated]
#     def get(self, request):
#         # 获取个人信息并返回
#         user = request.user
#         serializer = UserCenterInfoSerializer(user)
#
#         return Response(serializer.data)


# /GET /user/ 用户中心个人信息页优化
class UserCenterInfoView(RetrieveAPIView):
    # 用户必须登陆才能访问
    permission_classes = [IsAuthenticated]
    serializer_class = UserCenterInfoSerializer

    def get_object(self):
        return self.request.user

        # def get(self, request):
        #     # 获取个人信息并返回
        #     # user = request.user
        #     user = self.get_object()
        #     serializer = UserCenterInfoSerializer(user)
        #
        #     return Response(serializer.data)


class EmailView(UpdateAPIView):
    """用户邮箱设置"""
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSeriazlier

    def get_object(self):
        return self.request.user

        # def put(self, request):
        #     # 接受参数并校验
        #     # user = request.user
        #     user = self.get_object()
        #
        #     seriazlier = self.get_serializer(user, request.data)
        #
        #     seriazlier.is_valid(raise_exception=True)
        #
        #     # 发送激活邮件并保存邮箱保存
        #     seriazlier.save()
        #
        #     # 返回响应
        #     return Response(seriazlier.data)


class EmailAtiveView(APIView):
    """邮箱激活"""

    def put(self, request):
        # 接收参数并校验
        data = request.query_params.get('token')
        # 解密
        serializer = JWT(secret_key=settings.SECRET_KEY)
        try:
            res = serializer.loads(data)
        except BadData:
            return Response({'message': 'token无效'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取用户对象
        id = res.get('id')
        email = res.get('email')
        try:
            user = User.objects.get(id=id, email=email)
        except User.DoesNotExsit:
            return Response({'message': '用户不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 修改邮箱激活状态
        user.email_active = True
        user.save()
        return Response({'message': 'Ok'})


# # /addresses/ 新增地址
# class AddressAddView(GenericAPIView):
#     serializer_class = UserAddressSerializer
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request):
#         user = self.request.user
#         # 用户的收货地址数量不能超过二十个
#         count = user.addresses.count()
#
#         if count > USER_ADDRESS_COUNTS_LIMIT:
#             return Response({'message': '收货地址超过限制'}, status=status.HTTP_400_BAD_REQUEST)
#
#         # 接收数据并校验
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid()
#
#         # 保存数据
#         serializer.save()
#
#         # 序列化返回响应
#         return Response(serializer.data)


# /addresses/ 新增地址优化
class AddressAddView(GenericViewSet, CreateModelMixin, UpdateModelMixin):
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        user = self.request.user

        # 用户的收货地址数量不能超过二十个
        count = user.addresses.filter(is_deleted=False).count()

        if count > USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '收货地址超过限制'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

        # def post(self, request):
        #     # 接收数据并校验
        #     serializer = self.get_serializer(data=request.data)
        #     serializer.is_valid()
        #
        #     # 保存数据
        #     serializer.save()
        #
        #     # 序列化返回响应
        #     return Response(serializer.data)

    def list(self, request):
        # 获取所有收货地址
        # 查询所有的收或地址信息并返回
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    def destroy(self, request, *args, **kwargs):
        """删除收或地址"""
        # 获取收或地址对象
        # 逻辑删除
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """设置默认地址"""
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        """修改标题"""
        # 根据pk获取获取地址对象
        address = self.get_object()
        serializer = AddressTitleSerializer(address, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 设置用户标题
        serializer.save()

        return Response(serializer.data)


# # 用户历史浏览记录的添加
# class UserHistoryAdd(GenericAPIView):
#     serializer_class = UserHistorySerializer
#     permission_classes = [IsAuthenticated]
#
#     def post(self, request):
#         # 接受参数并校验
#         # 添加历史浏览到redis中
#         # 返回响应
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data, status=status.HTTP_201_CREATED)


# 用户历史浏览记录的添加代码优化
class UserHistoryAdd(CreateAPIView):
    serializer_class = UserHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 用户历史浏览记录的获取
        # 查询用户的历史浏览记录
        user = request.user

        con = get_redis_connection('history')
        key = 'history_%s' % user.id
        sku_ids = con.lrange(key, 0, -1)

        # 序列化并返回
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)
        serializer = UserHistoryAcquireSerializer(skus, many=True)
        return Response(serializer.data)


class UserLogin(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():

            # 登陆成功,调用合并购物车数据函数
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            # 合并购物车数据
            merge_cookie_cart_to_redis(request, user)
            # 请空cookie
            response.delete_cookie('cart')

            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
